package com.example.common.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * javabean转换工具类
 */
@SuppressWarnings("unused")
public class JsonUtil {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
            .setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    /**
     * 将对象转换为jsonString
     *
     * @param obj 对象
     * @return 字符串
     */
    public static String toJsonString(Object obj) {
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("转换jsonStr失败！");
        }
    }

    /**
     * 将单个对象转换成json格式的字符串（格式化后的json）
     *
     * @param obj 对象
     * @return 字符串
     */
    public static String toJsonPrettyString(Object obj) {
        try {
            return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (IOException e) {
            throw new RuntimeException("对象转换json失败！");
        }
    }

    /**
     * 将jsonString转换为List
     *
     * @param obj T
     * @return 集合
     */
    public static <T> List<T> toList(Class<T> obj, String jsonStr) {
        try {
            JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, obj);
            return OBJECT_MAPPER.readValue(jsonStr, javaType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("jsonStr序列化对象失败！");
        }
    }

    /**
     * jsonStr转实体对象
     *
     * @param obj T
     * @return 对象
     */
    public static <T> T toBean(Class<T> obj, String jsonStr) {
        try {
            return OBJECT_MAPPER.readValue(jsonStr, obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("jsonStr序列化对象失败！");
        }
    }
}
